import router from '@/router';
import axios from 'axios';
import { Message } from 'element-ui';

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' },
});

// 添加请求拦截器
request.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    let token = JSON.parse(sessionStorage.getItem('token')) || '';
    // config.headers['Authorization'] = token;
    config.headers['token'] = token;
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    console.log(error, 'error');
    return Promise.reject(error);
  }
);

// 添加响应拦截器
request.interceptors.response.use(
  (response) => {
    const msg = response.data.msg || '系统错误，请联系管理员';
    // 对响应数据做点什么
    if (response.data.code === 0 || response.data.code === 200) {
      return response.data;
    }
    if (response.data.code === 500) {
      Message({
        message: msg,
        type: 'error',
      });
      if(response.data,msg === '账号未登录'){
        sessionStorage.clear()
        localStorage.clear()
        router.push({
          path: '/login'
        }).catch(err=>{
          console.log(err)
        })
      }
      return Promise.reject(new Error(msg));
    } else {
      return response.data;
    }
  },
  (error) => {
    let { message } = error;
    if (message == 'Network Error') {
      message = '网络错误：' + message;
    } else if (message.includes('timeout')) {
      message = '请求超时：' + message;
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口错误：' + message;
    }
    Message({
      message: message,
      type: 'error',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

export default request;
